package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义权限过滤器
 * 在这里对整个微服务请求进行鉴权
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器主要执行的业务
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("=======执行了AuthFilter========");
        //1. 获取request请求
        ServerHttpRequest request = exchange.getRequest();

        //2. 获取响应response
        ServerHttpResponse response = exchange.getResponse();

        //3. 从请求头中获取token令牌
        String token = request.getHeaders().getFirst("token");

        //4. 判断令牌如果正确放行, 不正确, 抛出401权限不足异常
        if (token == null || "".equals(token)) {
            //响应中放入401权限不足状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回异常响应
            return response.setComplete();
        }

        //5. 放行到下一个过滤器或者微服务
        return chain.filter(exchange);
    }

    /**
     * 如果有多个过滤器, 那么会按照这个数字的顺序执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
